#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "lwip/sockets.h"
#include "esp_log.h"

static const char *TAG = "CONTROL";
#define CONTROL_PORT 8080

static bool is_streaming = true;

bool get_stream_status() { return is_streaming; }
void set_stream_status(bool enable) { is_streaming = enable; }

void control_task(void *pvParameters) {
    struct sockaddr_in dest_addr = {
        .sin_addr.s_addr = htonl(INADDR_ANY),
        .sin_family = AF_INET,
        .sin_port = htons(CONTROL_PORT),
    };

    int listen_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
    if (listen_sock < 0) {
        ESP_LOGE(TAG, "Unable to create socket");
        vTaskDelete(NULL);
        return;
    }

    int yes = 1;
    setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));

    if (bind(listen_sock, (struct sockaddr *)&dest_addr, sizeof(dest_addr)) != 0) {
        ESP_LOGE(TAG, "Socket bind failed");
        close(listen_sock);
        vTaskDelete(NULL);
        return;
    }

    if (listen(listen_sock, 1) != 0) {
        ESP_LOGE(TAG, "Listen failed");
        close(listen_sock);
        vTaskDelete(NULL);
        return;
    }

    ESP_LOGI(TAG, "Control Server Started on port %d", CONTROL_PORT);

    while (true) {
        struct sockaddr_in client_addr;
        socklen_t addr_len = sizeof(client_addr);
        int sock = accept(listen_sock, (struct sockaddr *)&client_addr, &addr_len);
        if (sock < 0) {
            ESP_LOGE(TAG, "Accept failed");
            continue;
        }

        ESP_LOGI(TAG, "Client connected");

        char rx_buffer[128];
        while (true) {
            int len = recv(sock, rx_buffer, sizeof(rx_buffer), 0);
            if (len <= 0) {
                ESP_LOGI(TAG, "Client disconnected");
                close(sock);
                break;
            }

            rx_buffer[len] = '\0';
            ESP_LOGI(TAG, "Received command: %s", rx_buffer);

            if (strncmp(rx_buffer, "play", 4) == 0) {
                set_stream_status(true);
                ESP_LOGI(TAG, "Stream resumed");
            } else if (strncmp(rx_buffer, "stop", 4) == 0) {
                set_stream_status(false);
                ESP_LOGI(TAG, "Stream paused");
            }
        }
    }
}

void start_control_server() {
    xTaskCreate(control_task, "tcp_control", 4096, NULL, 5, NULL);
}